<template>
  <div class="article-publish">
    <div class="container">
      <div class="publish-header">
        <h1>{{ isEdit ? '编辑文章' : '发布文章' }}</h1>
      </div>
      
      <div class="publish-form" v-loading="loading">
        <el-form
          :model="articleForm"
          :rules="articleRules"
          ref="articleFormRef"
          label-width="80px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
          </el-form-item>
          
          <el-form-item label="封面图">
            <el-upload
              class="cover-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleCoverChange"
            >
              <img v-if="articleForm.coverImage" :src="articleForm.coverImage" class="cover-image" />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">推荐尺寸：1200 x 400 像素，最大不超过 2MB</div>
          </el-form-item>
          
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="articleForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或创建标签"
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="内容" prop="content">
            <!-- 在实际项目中，建议使用Markdown编辑器或富文本编辑器 -->
            <el-input
              v-model="articleForm.content"
              type="textarea"
              :rows="15"
              placeholder="请输入文章内容..."
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">{{ isEdit ? '保存修改' : '发布文章' }}</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createArticle, updateArticle, getArticleDetail } from '../api/article'

const route = useRoute()
const router = useRouter()
const articleFormRef = ref<FormInstance>()
const loading = ref(false)
const submitting = ref(false)

// 判断是新建还是编辑
const isEdit = computed(() => !!route.query.id)

// 可用标签列表
const availableTags = ref([
  'Vue', 'React', 'Angular', 'JavaScript', 'TypeScript', 
  'Node.js', 'CSS', 'HTML', 'Webpack', 'Vite', 'Docker',
  '前端开发', '后端开发', '全栈开发', 'Web开发', '移动开发'
])

// 文章表单
const articleForm = reactive({
  title: '',
  content: '',
  coverImage: '',
  tags: [] as string[]
})

// 表单验证规则
const articleRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 50, message: '内容不能少于 50 个字符', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请至少选择一个标签', trigger: 'change' },
    { 
      validator: (rule: any, value: string[], callback: any) => {
        if (value.length > 5) {
          callback(new Error('最多选择 5 个标签'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 处理封面图上传
function handleCoverChange(file: any) {
  // 实际项目中，这里应该处理文件上传到服务器
  const fileReader = new FileReader()
  fileReader.onload = (e) => {
    if (e.target && e.target.result) {
      articleForm.coverImage = e.target.result as string
    }
  }
  fileReader.readAsDataURL(file.raw)
}

// 提交表单
async function submitForm() {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        submitting.value = true
        
        // 准备提交的数据
        const articleData = {
          title: articleForm.title,
          content: articleForm.content,
          tags: articleForm.tags,
          coverImage: articleForm.coverImage
        }
        
        if (isEdit.value) {
          // 编辑模式
          const id = route.query.id as string
          // 实际项目中，这里调用更新文章API
          // await updateArticle(id, articleData)
          
          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          ElMessage.success('文章更新成功')
        } else {
          // 新建模式
          // 实际项目中，这里调用创建文章API
          // await createArticle(articleData)
          
          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          ElMessage.success('文章发布成功')
        }
        
        // 跳转到个人中心
        router.push('/user')
      } catch (error) {
        console.error('发布/更新文章失败:', error)
        ElMessage.error('发布/更新文章失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 取消编辑
function cancelEdit() {
  ElMessageBox.confirm('确定要放弃编辑吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push(isEdit.value ? `/article/${route.query.id}` : '/user')
  }).catch(() => {})
}

// 获取文章详情（编辑模式）
async function fetchArticleDetail() {
  if (!isEdit.value) return
  
  const id = route.query.id as string
  
  try {
    loading.value = true
    
    // 实际项目中，这里调用获取文章详情API
    // const res = await getArticleDetail(id)
    
    // 模拟数据和API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟获取到的文章数据
    const mockArticle = {
      id,
      title: '如何使用Vue 3和TypeScript构建现代Web应用',
      content: `
Vue 3 是Vue.js的最新主要版本，它引入了许多新特性和改进，如组合式API、更好的TypeScript支持、更小的包体积等。

## 组合式API

组合式API是Vue 3引入的一个重要特性，它允许我们将相关的逻辑组合在一起，使代码更具可读性和可维护性。

\`\`\`typescript
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    
    function increment() {
      count.value++
    }
    
    onMounted(() => {
      console.log('组件已挂载')
    })
    
    return {
      count,
      increment
    }
  }
}
\`\`\`

## TypeScript集成

Vue 3提供了改进的TypeScript支持，使用TypeScript可以获得更好的开发体验和类型安全。
      `,
      tags: ['Vue', 'TypeScript', 'Web开发'],
      coverImage: id === '1' ? 'https://picsum.photos/id/30/1200/400' : ''
    }
    
    // 填充表单
    articleForm.title = mockArticle.title
    articleForm.content = mockArticle.content
    articleForm.tags = mockArticle.tags
    articleForm.coverImage = mockArticle.coverImage
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
    // 获取失败时返回个人中心
    router.push('/user')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (isEdit.value) {
    fetchArticleDetail()
  }
})
</script>

<style scoped lang="scss">
.article-publish {
  padding-top: 80px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.publish-header {
  margin-bottom: 20px;
  
  h1 {
    font-size: 24px;
    color: #303133;
  }
}

.publish-form {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 50px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  
  &:hover {
    border-color: #409eff;
  }
  
  .cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 30px;
    height: 30px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 